package controllers

import (
	"fmt"
	"github.com/flaravel/quanlaolao/app/models/promotion"
	"github.com/flaravel/quanlaolao/pkg/config"
	"github.com/flaravel/quanlaolao/pkg/flash"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"github.com/flaravel/quanlaolao/pkg/upload"
	"github.com/flaravel/quanlaolao/pkg/view"
	"github.com/syyongx/php2go"
	"net/http"
)

type LiebianController struct {
	BaseController
}

func (c LiebianController) Index(w http.ResponseWriter, r *http.Request)  {
	data,pageData,err := promotion.GetAll(r,10)
	if err != nil {
		c.ResposeForSQLError(w,err)
	} else {
		view.Render(w,view.D{
			"Data": data,
			"PagerData": pageData,
		},"promotion.index")
	}
}


func (c LiebianController) Create(w http.ResponseWriter, r *http.Request)  {
	view.Render(w, view.D{
	}, "promotion.create", "promotion._form_field")
}

func (c LiebianController) Store(w http.ResponseWriter, r *http.Request)  {
	var errors map[string][]string
	r.ParseMultipartForm(32 << 20)
	_liebian := promotion.GroupPromotion{
		Name:     r.PostFormValue("name"),
		Desc:     r.PostFormValue("desc"),
		Number:   types.StringToInt(r.PostFormValue("number")),
	}

	// 群头像
	file, header, err := r.FormFile("avatar")
	if err == nil {
		avatar, errs := upload.UploadImage(file,header,"liebian")
		if errs != nil {
			errors["avatar"] = []string{errs.Error()}
		}
		_liebian.Avatar = avatar
	}

	// 群二维码
	qrcode, qrcode_header, err := r.FormFile("wechat_qr_code")
	if err == nil {
		wechat_qr_code, errs := upload.UploadImage(qrcode,qrcode_header,"liebian")
		if errs != nil {
			errors["wechat_qr_code"] = []string{errs.Error()}
		}
		_liebian.WechatQrCode = wechat_qr_code
	}

	// 分享二维码
	shareQrCode,shareQrCodeHeader, err := r.FormFile("url_qr_code")
	if err == nil {
		urlQrCode, errs := upload.UploadImage(shareQrCode,shareQrCodeHeader,"liebian")
		if errs != nil {
			errors["url_qr_code"] = []string{errs.Error()}
		}
		_liebian.UrlQrCode = urlQrCode
	}

	if len(errors) == 0 {
		// 创建文章
		_liebian.Create()
		if _liebian.ID > 0 {
			flash.Success("群裂变创建成功")
			indexURL := route.Name2URL("liebian.index")

			// 群成员头像
			groupAvatars := r.MultipartForm.File["group_avatar"]
			if len(groupAvatars) > 0 {
				for _, v := range groupAvatars {
					file,_ := v.Open()
					group_avatar_url, _ := upload.UploadImage(file,v,"liebian")
					_group_avatar := promotion.GroupAvatar{
						Avatar:    group_avatar_url,
						GroupId:   _liebian.ID,
					}
					_group_avatar.AvatarCreate()
				}
			}
			// 群内容
			contents := []byte(r.PostFormValue("content"))

			var result []map[string]interface{}
			_ = php2go.JSONDecode(contents, &result)
			if len(result) > 0 {
				for _, v := range result {
					fmt.Println(v)
					_liebian_content := promotion.GroupContent{
						GroupId: _liebian.ID,
						Content: v["content"].(string),
						IsRight: int(v["is_right"].(float64)),
					}
					_ = _liebian_content.Create()
				}
			}
			_liebian.Url = fmt.Sprintf("%s/%s",config.GetString("app.liebian_url"),types.IdEncode(int(_liebian.ID)))
			_liebian.Update()
			http.Redirect(w, r, indexURL, http.StatusFound)
		} else {
			flash.Danger("群裂变创建失败")
			view.Render(w, view.D{
				"Liebian": _liebian,
				"Errors":  errors,
			}, "promotion.create", "promotion._form_field")
		}
	} else {
		view.Render(w, view.D{
			"Liebian": _liebian,
			"Errors":  errors,
		}, "promotion.create", "promotion._form_field")
	}
}

func (c LiebianController) Delete(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id",r)

	_cps , err := promotion.Get(id)
	if err != nil {
		c.ResposeForSQLError(w,err)
	} else {
		rowsAffected, err := _cps.Delete()
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "500 服务器内部错误")
		} else {
			if rowsAffected > 0 {
				flash.Success("删除成功")
				indexURL := route.Name2URL("liebian.index")
				http.Redirect(w, r, indexURL, http.StatusFound)
			} else {
				w.WriteHeader(http.StatusNotFound)
				fmt.Fprint(w, "404 未找到")
			}
		}
	}
}